<template>
  <div>
    展示在线用户<br>
    <ul>
        <li v-for="i in userlist">
            <el-button @click="choseid(i.id)">{{i.name}}</el-button>
        </li>
    </ul>

    <el-input v-model="msg"></el-input>
    <el-button @click="submit">提交</el-button>
    聊天内容展示:
    <ul>
      <li v-for="i in meslist">{{ i }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userid:'',
      ws: null,
      msg: "",
      username: '',
      meslist: [],
      userlist:[],
      choseuserid:''
    };
  },
  methods: {
    initw() {
      this.userid = this.$route.query.userid
      this.username = "客服"+this.userid
      this.ws = new WebSocket(
        "ws://localhost:8000/ws?userid=" +
          this.userid +
          "&name=" +
          this.username
      );
      this.ws.onopen = function () {
        alert("success");
      };
      this.ws.onmessage = (msg) => {
        var mes = JSON.parse(msg.data);
        this.meslist.push(mes["mes"]);
        this.userlist=mes["userlist"]
      };
    },
    submit() {
      if (this.choseuserid){
        var mes = this.username + "说:" + this.msg;
        this.meslist.push(mes);
        var sendsms = JSON.stringify({"id":this.choseuserid,"mes":mes})
        this.ws.send(sendsms);
      }else{
        alert("必须选择聊天用户")
      }
    },
    choseid(id){
        this.choseuserid = id
    }
  },
  mounted(){
    this.initw()
  }
};
</script>

<style>
</style>